package com.project.springboot.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * description: zip压缩工具类
 * @author 朱正磊
 * @date 2023-12-18 14:31:16
 */
public class ZipUtil {

    /**
     * description: 多个文件压缩成zip文件
     * @author 朱正磊
     * @date 2023-12-18 15:23:39
     * @param zipPathDir 压缩包路径 ，如 /home/data/zip-folder/
     * @param zipFileName 压缩包名称 ，如 测试文件.zip
     * @param fileList 要压缩的文件列表（绝对路径），如 /home/person/test/测试.doc，/home/person/haha/测试.doc
     */
    public static void compressFiles(String zipPathDir, String zipFileName, List<String> fileList) {
        try {
            FileOutputStream outputStream = new FileOutputStream(zipPathDir + zipFileName);
            ZipOutputStream zos = new ZipOutputStream(outputStream);
            File zipFile = new File(zipPathDir);
            if (!zipFile.exists()) {
                // 如果文件夹不存在就创建
                boolean mkdirs = zipFile.mkdirs();
                if (!mkdirs) {
                    throw new RuntimeException("创建文件夹失败！");
                }
            }
            for (String filePath : fileList) {
                File file = new File(filePath);
                if (file.exists()) {
                    int index = file.getName().lastIndexOf('.');
                    String fileName = file.getName().substring(0, index) + "-" + dateRandom18() + file.getName().substring(index);
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zos.putNextEntry(zipEntry);
                    byte[] buffer = new byte[2048];
                    compressSingleFile(file, zos, buffer);
                }
            }
            zos.flush();
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("压缩多个文件成zip异常：" + e.getMessage());
        }
    }

    /**
     * description: 压缩单个文件
     * @author 朱正磊
     * @date 2023-12-18 14:42:35
     * @param file 待压缩的文件
     * @param zos zip输出流
     * @param buffer 缓冲区
     */
    public static void compressSingleFile(File file, ZipOutputStream zos, byte[] buffer) {
        int len;
        try (FileInputStream fis = new FileInputStream(file)) {
            while ((len = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, len);
                zos.flush();
            }
            zos.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("压缩单个文件异常：" + e.getMessage());
        }
    }

    /**
     * description: 生成随机数
     * @author 朱正磊
     * @date 2023-12-18 14:42:24
     * @return 返回18位随机数
     */
    public static String dateRandom18() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        String timeMillis = String.valueOf(System.currentTimeMillis());
        String fiveNumber = timeMillis.substring(timeMillis.length() - 6);
        String tempRandom = String.valueOf(Math.random());
        String number = tempRandom.substring(tempRandom.length() - 4);
        return date + fiveNumber + number;
    }

    /**
     * description: 测试方法
     * @author 朱正磊
     * @date 2023-12-18 14:42:16
     * @param args 参数
     */
    public static void main(String[] args) {
        String zipPathDir = "F:/zzl/workfile/图片/卡通/";
        String zipFileName = "test.zip";
        List<String> list = new ArrayList<>();
        list.add("F:/zzl/workfile/图片/卡通/katong.jpeg");
        list.add("F:/zzl/workfile/图片/其他/fengjing.gif");
        list.add("F:/zzl/workfile/图片/药品/黄芩.jpeg");
        compressFiles(zipPathDir, zipFileName, list);
    }

}
